﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sykj.Infrastructure;
using System.Linq.Dynamic.Core;
using Sykj.ViewModel;
using Microsoft.EntityFrameworkCore;

namespace Sykj.Services
{
    /// <summary>
    /// 用户帐号信息
    /// </summary>
    public class Users : Sykj.Repository.RepositoryBase<Sykj.Entity.Users>, Sykj.IServices.IUsers
    {

        ICacheService _cacheService;
        public Users(Sykj.Repository.SyDbContext dbcontext, ICacheService cacheService) : base(dbcontext)
        {
            _cacheService = cacheService;
        }

        #region 添加用户和角色
        /// <summary>
        /// 添加用户和角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddRoles(Sykj.Entity.Users model)
        {
            //创建事物
            var tran = _dbContext.Database.BeginTransaction();
            try
            {
                model.Password = Infrastructure.DESEncrypt.Encrypt(model.Password);
                model.UserType = "AA";
                model.Creator = 0;
                model.CreateDate = DateTime.Now;

                //添加用户信息
                base.Add(model, false);
                int i = _dbContext.SaveChanges();

                //添加角色
                if (model.RoleIds.Count > 0)
                {
                    foreach (var item in model.RoleIds)
                    {
                        _dbContext.UserRoles.Add(new Entity.UserRoles { RoleID = item, UserID = model.UserId });
                        int i1 = _dbContext.SaveChanges();
                    }
                }

                tran.Commit();
                return true;
            }
            catch
            {
                tran.Rollback();
                return false;
            }
        }
        #endregion

        #region  用户名是否存在
        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public bool IsExists(string userName)
        {
            return base.IsExist(c => c.UserName == userName);
        }
        #endregion

        #region 通过unionId获取用户
        /// <summary>
        /// 通过unionId获取用户
        /// </summary>
        /// <param name="unionId"></param>
        /// <returns></returns>
        public bool IsExistsUnionId(string unionId)
        {
            return base.IsExist(c => c.UnionId == unionId);
        }
        #endregion

        #region 检测登录
        /// <summary>
        /// 检测登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public ApiResult ValidateLogin(string userName, string passWord)
        {
            ApiResult res = new ApiResult();
            try
            {
                string s = DESEncrypt.Encrypt(passWord);
                Sykj.Entity.Users model = base.GetModel(c => c.UserName == userName && c.Password == s);
                if (model == null)
                {
                    res.success = false;
                    res.code = (int)ApiEnum.Error;
                    res.msg = "帐号或密码错误~";
                }
                else
                {
                    res.success = true;
                    res.msg = "登录成功~";
                    res.data = model;
                    res.code = (int)ApiEnum.Status;
                }
            }
            catch (Exception ex)
            {
                res.msg = ApiEnum.Error.GetEnumText() + ex.Message;
                res.code = (int)ApiEnum.Error;
            }
            return res;
        }
        #endregion

        #region 根据用户获取角色列表
        /// <summary>
        /// 根据用户获取角色列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Sykj.Entity.Roles> GetRoleList(int userId)
        {
            //linq写法
            var list = from userRoles in _dbContext.UserRoles
                       join roles in _dbContext.Roles on userRoles.RoleID equals roles.RoleId
                       where userRoles.UserID == userId
                       select roles;

            return list.ToList();
        }
        #endregion

        #region  根据用户获取权限列表
        /// <summary>
        /// 根据用户获取权限列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="rolesList">用户所属的角色列表</param>
        /// <returns></returns>
        public List<Sykj.Entity.Permissions> GetPermissionsList(int userId, List<Sykj.Entity.Roles> rolesList)
        {
            List<Sykj.Entity.Permissions> list = new List<Entity.Permissions>();
            if (_cacheService.Exists(CacheKey.USERPERMISSIONSLIST))
            {
                list = _cacheService.GetCache<List<Sykj.Entity.Permissions>>(CacheKey.USERPERMISSIONSLIST);
            }
            else
            {
                var l = from rolePermissions in _dbContext.Rolepermissions
                        join permissions in _dbContext.Permissions
                        on rolePermissions.PermissionId equals permissions.PermissionId
                        select new Sykj.Entity.Permissions()
                        {
                            PermissionId = permissions.PermissionId,
                            CreateDate = permissions.CreateDate,
                            Depth = permissions.Depth,
                            Description = permissions.Description,
                            Icon = permissions.Icon,
                            IsEnable = permissions.IsEnable,
                            ParentId = permissions.ParentId,
                            Path = permissions.Path,
                            Sort = permissions.Sort,
                            Title = permissions.Title,
                            Type = permissions.Type,
                            Url = permissions.Url,
                            RoleId = rolePermissions.RoleId
                        };

                list = l.AsNoTracking().ToList();
                _cacheService.SetCache(CacheKey.USERPERMISSIONSLIST, list);
            }
            List<int> rs = rolesList.Select(c => c.RoleId).ToList();
            var result = from a in list where rs.Contains(a.RoleId) select a;
            return result.ToList();
        }
        #endregion

        #region 修改用户和角色
        /// <summary>
        /// 修改用户和角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateUserRole(Sykj.Entity.Users model)
        {
            //删除之前的设置
            var roles = _dbContext.UserRoles.Where(c => c.UserID == model.UserId);
            _dbContext.UserRoles.RemoveRange(roles);

            //更新用户信息
            Update(model, false);

            //添加角色ID
            if (model.RoleIds != null || model.RoleIds.Count > 0)
            {
                foreach (var item in model.RoleIds)
                {
                    _dbContext.UserRoles.Add(new Entity.UserRoles { RoleID = item, UserID = model.UserId });
                }
            }

            int row = _dbContext.SaveChanges();
            return (row > 0);
        }
        #endregion

        #region 管理后台查询
        /// <summary>
        /// 管理后台查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="predicate">条件</param>
        /// <param name="ordering">排序</param>
        /// <param name="args">条件参数</param>
        /// <returns></returns>
        public IQueryable GetPagedListExt(int pageIndex, int pageSize, string predicate, string ordering, params object[] args)
        {
            var result = (from p in _dbContext.Users
                          select new
                          {
                              p.UserId,
                              p.UserName,
                              p.TrueName,
                              p.Phone,
                              p.Activity,
                              p.CreateDate
                          }).AsQueryable();

            if (!string.IsNullOrWhiteSpace(predicate))
                result = result.Where(predicate, args);

            if (!string.IsNullOrWhiteSpace(ordering))
                result = result.OrderBy(ordering);

            return result.Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }
        #endregion
    }
}
